﻿using UnityEngine;
using System.Collections;

public class CharacterControllerScript : MonoBehaviour {

	public Transform groundCheck;
	public Transform faceCheck;
	public LayerMask whatIsGround;

	public float jumpForce = 70f;
	public float maxSpeed = 10f;
	public float runningTreshholdPercentage = 40f;
	
	Animator anim;

	bool facingLeft = true;
	bool grounded = false;
	bool isRunning = false;
	float groundRadius = 0.2f;


	// Use this for initialization
	void Start () {
		anim = GetComponent<Animator> ();
	}
	
	// Update is called once per frame
	void Update () {
		if (grounded && Input.GetKeyDown (KeyCode.Space)) 
		{
			anim.SetBool("Ground", false);
			rigidbody2D.AddForce(new Vector2(0, isRunning ? jumpForce * 1.3f : jumpForce));
		}
		if (grounded) 
		{
			isRunning = Input.GetKey (KeyCode.LeftShift);
		}
	}

	void FixedUpdate () {
		// Check if grounded and update animator
		grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
		anim.SetBool ("Ground", grounded);

		anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);


		// Move character
		float move = Input.GetAxis ("Horizontal");
		float relativeSpeed = move * maxSpeed;
		if (!isRunning)
		{
			relativeSpeed *= (runningTreshholdPercentage * 0.01f);
		}

		anim.SetFloat ("Speed", Mathf.Abs (relativeSpeed));

		if (!Physics2D.OverlapCircle (faceCheck.position, groundRadius, whatIsGround)) 
		{
			rigidbody2D.velocity = new Vector2 (relativeSpeed, rigidbody2D.velocity.y);
		}

		if (move > 0 && facingLeft)
			Flip ();
		else if (move < 0 && !facingLeft)
			Flip ();

	}

	void Flip()
	{
		facingLeft = !facingLeft;
		Vector3 scale = transform.localScale;
		scale.x *= -1;
		transform.localScale = scale;
	}
}
